package edu.hit.pact.pgse.crawler.send;

import java.net.InetSocketAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import edu.hit.pact.pgse.communication.message.CrawlerDirReplyMessage;
import edu.hit.pact.pgse.communication.message.Types;

public class StoreNodeQueryHandler extends IoHandlerAdapter{
	private Log logger;
	private InetSocketAddress storeAddr;
	private boolean isNewMessage = false;
	
	
	public boolean isNewMessage() {
		return isNewMessage;
	}

	public void setNewMessage(boolean isNewMessage) {
		this.isNewMessage = isNewMessage;
	}

	public StoreNodeQueryHandler(){
		this.logger = LogFactory.getLog(StoreNodeQueryHandler.class);
		System.out.println("handler is created");
	}

	public InetSocketAddress getStoreAddr() {
		return storeAddr;
	}

	public void setStoreAddr(InetSocketAddress storeAddr) {
		this.storeAddr = storeAddr;
	}

	/*
	 * (non-Javadoc)
	 * @see org.apache.mina.core.service.IoHandlerAdapter#sessionOpened(org.apache.mina.core.session.IoSession)
	 */
	public void sessionOpened(IoSession session) {
		logger.info("session open");
	}//end for
	
    public void sessionCreated(IoSession session) {
    	// set idle time to MAX_IDLE_TIME seconds
    	System.out.println("session created");
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE,60);//seconds
    }
    
    /*
     * (non-Javadoc)
     * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object)
     */
    @Override
    public void messageReceived(IoSession session, Object message) {
    	System.out.println("message receive");
    	 logger.info("received: " + message);
    	 CrawlerDirReplyMessage reply = (CrawlerDirReplyMessage)message;
    	 if (reply.getType() != Types.CRAWEL_DIR_REPLY){
    		 logger.error("wrong message type");
    		 return;
    	 }
    	 logger.info(reply.getAddr());
    	 this.storeAddr = reply.getAddr();
    	 this.isNewMessage = true;
    }
	
    @Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.error("session is closed");
		session.close(true);
	}
    
	/*
	 * (non-Javadoc)
	 * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(org.apache.mina.core.session.IoSession, java.lang.Throwable)
	 */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        logger.warn("Unexpected exception.", cause);
        // Close connection when unexpected exception is caught.
        session.close(true);
    }
}
